
import { reactive, ref, onUnmounted } from 'vue';

export function useDraggable(iconSize = 32, clickCallback?: () => void) {
  
  const dragPosition = reactive({
    x: window.innerWidth - iconSize,
    y: window.innerHeight * 0.85,
  });
  const isDragging = ref(false);
  const initialPosition = reactive({ x: 0, y: 0 });
  const dragStartPosition = reactive({ x: 0, y: 0 });

  
  const startDrag = (event: MouseEvent | TouchEvent) => {
    event.preventDefault();
    event.stopPropagation();

    
    initialPosition.x = dragPosition.x;
    initialPosition.y = dragPosition.y;
    const point = 'touches' in event ? event.touches[0] : event;
    dragStartPosition.x = point.clientX;
    dragStartPosition.y = point.clientY;

    isDragging.value = true;

    
    if (event.type === 'mousedown') {
      document.addEventListener('mousemove', handleDrag);
      document.addEventListener('mouseup', stopDrag);
    } else {
      document.addEventListener('touchmove', handleDrag, { passive: false });
      document.addEventListener('touchend', stopDrag);
    }
  };

  
  const handleDrag = (event: MouseEvent | TouchEvent) => {
    if (!isDragging.value) return;
    event.preventDefault();

    const point = 'touches' in event ? event.touches[0] : event;
    const deltaX = point.clientX - dragStartPosition.x;
    const deltaY = point.clientY - dragStartPosition.y;

    let newX = initialPosition.x + deltaX;
    let newY = initialPosition.y + deltaY;

    
    newX = Math.max(0, Math.min(window.innerWidth - iconSize, newX));
    newY = Math.max(0, Math.min(window.innerHeight - iconSize, newY));

    dragPosition.x = newX;
    dragPosition.y = newY;
  };

  
  const stopDrag = (event: MouseEvent | TouchEvent) => {
    
    const point = 'changedTouches' in event ? event.changedTouches[0] : event;
    const dx = point.clientX - dragStartPosition.x;
    const dy = point.clientY - dragStartPosition.y;
    const dist = Math.hypot(dx, dy);

    if (dist < 5 && typeof clickCallback === 'function') {
      clickCallback();
    }

    isDragging.value = false;
    document.removeEventListener('mousemove', handleDrag);
    document.removeEventListener('mouseup', stopDrag);
    document.removeEventListener('touchmove', handleDrag);
    document.removeEventListener('touchend', stopDrag);
  };

  
  onUnmounted(() => {
    document.removeEventListener('mousemove', handleDrag);
    document.removeEventListener('mouseup', stopDrag);
    document.removeEventListener('touchmove', handleDrag);
    document.removeEventListener('touchend', stopDrag);
  });

  return {
    dragPosition,
    startDrag,
  };
}
